const PARAGRAPH_INDENTNAME = 'PARAGRAPH_INDENTNAME' // 段落缩进
const TEXT_INDENTNAME = 'TEXT_INDENTNAME'; // 首行缩进
const TEXT_UNDENLINE = 'TEXT_UNDENLINE' // 下划线


function createParagraphIndent(start, item) {
  return {
    type: 'paragraph',
    styleName: PARAGRAPH_INDENTNAME,
    children: [item],
    indent: { start },
  }
}

// function createTextIndent(children) {
//   return {
//     type: 'paragraph',
//     styleName: TEXT_INDENTNAME,
//     children
//   }
// }

function popStack(stack, item) {
  let len = stack.length;
  while (len) {
    let last = stack.pop();
    len--;
    if (item && last.indent.start === parseInt(item.indent.start)) {
      last.children.push(item)
      return
    }
    if (len) {
      stack[len - 1].children.push(last)
    }
    
  }
}
function transformDocument(element) {
  if (element.children) {
    let len = element.children.length
    let stack = []

    element.children = element.children.reduce((prev, item, index) => {

      item = transformDocument(item)
      let flag = false
      if (item.type === 'paragraph') {
        let indent = item.indent;
        let start = parseInt(indent && indent.start);
        //let firstLine = parseInt(indent && indent.firstLine);

        // if (!isNaN(firstLine) && firstLine > 0) {
        //   item.children = [createTextIndent(item.children)]
        // }

        if (!isNaN(start) && start > 0) {
          if (start > 0) {
            flag = true
            let len = stack.length
            if (len) {
              let last = stack[len - 1]
              let curStart = last.indent.start
              if (curStart === start) {
                last.children.push(item)
              } else {
                let cur = createParagraphIndent(start, item)
                if (curStart < start) {
                  stack.push(cur)
                } else {
                  popStack(stack, item)
                }
              }
            } else {
              let cur = createParagraphIndent(start, item)
              stack.push(cur)
              prev.push(cur)
            }
          }
        }
      } else if (item.type === 'run') {
        if (item.isUnderline) {
          item.styleName = TEXT_UNDENLINE
        }
      }

      if (!flag) {
        prev.push(item)
        popStack(stack)
      }
      if (index === len - 1) {
        popStack(stack)
      }
      return prev
    }, [])
  }
  return element
}

module.exports = {
  transformDocument,
  PARAGRAPH_INDENTNAME,
  TEXT_INDENTNAME,
  TEXT_UNDENLINE
}
